# Copyright (C) 2025 All rights reserved.
#     
# @File wxwork_user_doc.py
# @Brief 
# @Author 杨嘉祥, vnimy@mediad.cn
# @Version 1.0
# @Date 2025-01-26
#

import frappe
from frappe.model.document import Document
from frappe_wxwork.utils.contact_sync import WXWorkContactSync


class WXWorkUser(Document):

    from typing import TYPE_CHECKING

    if TYPE_CHECKING:
        from frappe.types import DF
                
        corpid: DF.Data
        userid: DF.Data
        user: DF.Link | None
        
    def validate(self):
        if self.is_new():
            if frappe.db.exists("WXWork User", {"corpid": self.corpid, "userid": self.userid}):
                frappe.throw(f"已存在用户：{self.corpid} - {self.userid}")
        else:
            if frappe.db.exists("WXWork User", {"corpid": self.corpid, "userid": self.userid, "name": ["!=", self.name]}):
                frappe.throw(f"已存在用户：{self.corpid} - {self.userid}")

    @frappe.whitelist()
    def create_user(self):
        if not self.supplier and not self.customer: return
        # 创建用户分派角色
        email = f"{self.userid}@dummy.cc"
        if frappe.db.exists("User", email):
            user_doc = frappe.get_doc("User", email)
        else:
            user_doc = frappe.new_doc("User")
            # 禁用内部用户功能
            fields = [
                "search_bar",
                "notifications",
                "list_sidebar",
                "bulk_actions",
                "view_switcher",             
                "form_sidebar",
                "timeline",
                "dashboard",
                "thread_notify",
                "allowed_in_mentions"
            ]
            for field in fields:
                user_doc.set(field, 0)
            user_doc.email = email
            user_doc.first_name = self.wechat_nickname
            user_doc.send_welcome_email = 0
            # user_doc.name = self.userid
            # user_doc.flags.name_set = True
            default_role = frappe.db.get_single_value("WXWork Settings", "default_role")
            if not default_role:
                if self.supplier:
                    default_role = "Supplier"
                elif self.customer:
                    default_role = "Customer"
            user_doc.add_roles([default_role])
    
        # 2. 关联微信用户
        self.user = user_doc.name
        self.active = 1
        # 3. 关联供应商
        if self.supplier:
            self.add_portal_user_and_user_permission("Supplier", self.supplier, user_doc.name)
        # 3. 关联客户
        if self.customer:
            self.add_portal_user_and_user_permission("Customer", self.customer, user_doc.name)

        self.save()

    def add_portal_user_and_user_permission(self, partner_type, partner, user):
        partner_doc = frappe.get_doc(partner_type, partner)
        partner_doc.append("portal_users", {"user": user})
        partner_doc.save()

        user_permission_doc = frappe.new_doc("User Permission")
        user_permission_doc.update({
            "user": user,
            "allow": partner_type,
            "for_value": partner,
            "apply_to_all_doctypes": 1
        })
        user_permission_doc.insert(ignore_permissions=1)

@frappe.whitelist()
def sync_contacts():
    """同步通讯录"""
    try:
        sync = WXWorkContactSync()
        result = sync.sync_all_contacts()
        
        if result.get("success"):
            frappe.msgprint(result.get("message"))
        else:
            frappe.msgprint(f"同步失败: {result.get('error')}")
            
        return result
        
    except Exception as e:
        frappe.log_error(f"同步通讯录失败: {str(e)}")
        frappe.msgprint(f"同步失败: {str(e)}")
        return {"success": False, "error": str(e)}

@frappe.whitelist()
def test_connection():
    """测试连接"""
    try:
        sync = WXWorkContactSync()
        result = sync.test_connection()
        return result
    except Exception as e:
        return {"success": False, "message": str(e)}
